package com.winshare.saleAssistant.service.impl;

import com.winshare.saleAssistant.constant.ArticleStatus;
import com.winshare.saleAssistant.constant.ReadStatus;
import com.winshare.saleAssistant.dao.ArticleMapper;
import com.winshare.saleAssistant.dao.FeedbackMapper;
import com.winshare.saleAssistant.dao.StaffMapper;
import com.winshare.saleAssistant.domain.dto.resp.OrganizationRespDTO;
import com.winshare.saleAssistant.domain.entity.*;
import com.winshare.saleAssistant.domain.query.ArticleQuery;
import com.winshare.saleAssistant.domain.dto.req.*;
import com.winshare.saleAssistant.domain.dto.resp.ArticlePreviewDTO;
import com.winshare.saleAssistant.domain.dto.resp.ArticleRespDTO;
import com.winshare.saleAssistant.exception.BusinessException;
import com.winshare.saleAssistant.mapper.ArticleMapStruct;
import com.winshare.saleAssistant.mapper.ProductMapStruct;
import com.winshare.saleAssistant.service.ArticleService;
import com.winshare.saleAssistant.service.OrganizationService;
import com.winshare.saleAssistant.service.StatisticsService;
import com.winshare.saleAssistant.util.Page;
import com.winshare.saleAssistant.util.RequestHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl implements ArticleService {

    private final ArticleMapper articleMapper;

    private final FeedbackMapper feedbackMapper;

    private final StatisticsService statisticsService;

    private final OrganizationService organizationService;

    private final StaffMapper staffMapper;


    public ArticleServiceImpl(StaffMapper staffMapper, ArticleMapper articleMapper, FeedbackMapper feedbackMapper,
                              StatisticsService statisticsService, OrganizationService organizationService) {
        this.staffMapper = staffMapper;
        this.articleMapper = articleMapper;
        this.feedbackMapper = feedbackMapper;
        this.statisticsService = statisticsService;
        this.organizationService = organizationService;
    }

    @Override
    public void save(ArticleCreateDTO articleCreateDTO) {
        ArticleDO articleDO = ArticleMapStruct.INSTANCE.fromArticleCreateDTO(articleCreateDTO);
        if (checkArticleTitleExist(articleDO)) {
            throw new BusinessException("系统中已经存在同样标题的文章");
        }
        articleDO.setAuditOrgId(null);
        articleDO.setAuditPerson(null);
        articleDO.setCreateTime(LocalDateTime.now().toString());
        articleDO.setCreator(RequestHolder.getCurrentUser().getStaffName());
        articleDO.setOrgId(RequestHolder.getCurrentUser().getOrgId());
        List<String> labelList = articleCreateDTO.getArticleLabelList();
        if (!CollectionUtils.isEmpty(labelList)) {
            articleDO.setArticleLabel(labelList.stream().collect(Collectors.joining(",")));
        }
        articleMapper.saveArticle(articleDO);
        // 不需要特定的审核人和审核机构，默认为自己部门
//        if(articleCreateDTO.validAuditInfo()) {
//            ArticleDO articleDOInSql = articleMapper.getArticle(articleDO);
//            ArticleIdDTO articleIdDTO = new ArticleIdDTO();
//            articleIdDTO.setAuditOrgId(articleCreateDTO.getAuditOrgId());
//            articleIdDTO.setAuditOrgName(articleCreateDTO.getAuditOrgName());
//            articleIdDTO.setId(articleDOInSql.getId());
//            submitArticle(articleIdDTO);
//        }
    }


    @Override
    public void update(ArticleUpdateDTO articleUpdateDTO) {
        ArticleDO articleDO = ArticleMapStruct.INSTANCE.fromArticleUpdateDTO(articleUpdateDTO);
        ArticleDO articleDOCondition = new ArticleDO();
        articleDOCondition.setArticleTitle(null);
        articleDOCondition.setId(articleDO.getId());
        ArticleDO articleDOInSql = articleMapper.getArticle(articleDOCondition);
        if (null == articleDOInSql) {
            throw new BusinessException("当前文章不存在");
        }
        if (4 == articleDOInSql.getStatus()) {
            throw new BusinessException("已发布或审核通过的文章不能被修改");
        }
        articleDO.setAuditOrgId(null);
        articleDO.setAuditPerson(null);
        List<String> labelList = articleUpdateDTO.getArticleLabelList();
        if (!CollectionUtils.isEmpty(labelList)) {
            articleDO.setArticleLabel(labelList.stream().collect(Collectors.joining(",")));
        }
        articleMapper.updateArticle(articleDO);
        // 不需要特定的审核人和审核机构，默认为自己部门
//        if(articleUpdateDTO.validAuditInfo()) {
//            ArticleIdDTO articleIdDTO = ArticleMapStruct.INSTANCE.fromArticleDO1(articleDO);
//            submitArticle(articleIdDTO);
//        }
    }

    @Override
    public void delete(ArticleDeleteDTO articleDeleteDTO) {
        ArticleDO articleDO = ArticleMapStruct.INSTANCE.fromArticleDeleteDTO(articleDeleteDTO);
        ArticleDO articleDOInSql = articleMapper.getArticle(articleDO);
        if (null == articleDOInSql) {
            throw new BusinessException("当前文章不存在");
        }
        if (articleDOInSql.getStatus() == ArticleStatus.auditing || articleDOInSql.getStatus() == ArticleStatus.passed) {
            throw new BusinessException("只有草稿或已被驳回状态的文章才能被删除");
        }
        articleMapper.deleteArticle(articleDO);
    }

    @Override
    public Page<ArticleRespDTO> getArticleList(ArticleQueryDTO articleQueryDTO) {
        ArticleQuery articleQuery = ArticleMapStruct.INSTANCE.fromArticleQueryDTO(articleQueryDTO);
        articleQuery.setOffsetIndex(articleQueryDTO.getOffsetIndex());
        if (Objects.equals(RequestHolder.getCurrentUser().getSourceType(), "mini")) {
            articleQuery.setOrgIdList(null);
        } else {
            List<Integer> orgIdList = organizationService.getChildrenOrgList(RequestHolder.getCurrentUser().getOrgId(), null);
            articleQuery.setOrgIdList(orgIdList);
        }
        if (!StringUtils.isEmpty(articleQueryDTO.getArticleLabel())) {
            articleQuery.setArticleLabelList(Arrays.asList(articleQueryDTO.getArticleLabel().split(",")));
        }
        int totalCount = articleMapper.queryArticleCount(articleQuery);
        Integer pageIndex = articleQueryDTO.getPageIndex();
        Integer pageSize = articleQueryDTO.getPageSize();
        if (0 == totalCount) {
            return new Page<>(pageIndex, pageSize, totalCount, new ArrayList<>());
        }
        if (articleQueryDTO.getIsMe() == 0) {
            articleQuery.setCreator(null);
        } else {
            articleQuery.setCreator(RequestHolder.getCurrentUser().getStaffName());
        }
        List<ArticleDO> articleDOList = articleMapper.findArticleListByConditions(articleQuery);
        List<ArticleRespDTO> articleRespDTOList = ArticleMapStruct.INSTANCE.fromArticleDOList(articleDOList);
        return new Page<>(pageIndex, pageSize, totalCount, articleRespDTOList);
    }

    @Override
    public void cancelArticle(BaseIdDTO articleIdDTO) {
        ArticleDO articleDO = ArticleMapStruct.INSTANCE.fromBaseIdDTO(articleIdDTO);
        ArticleDO articleDOInSql = articleMapper.getArticle(articleDO);
        if (null == articleDOInSql) {
            throw new BusinessException("当前文章不存在。");
        }
        if (articleDOInSql.getStatus().intValue() == ArticleStatus.passed) {
            if (Objects.equals(RequestHolder.getCurrentUser().getStaffName(), articleDOInSql.getIssuePerson())) {
                articleDO.setStatus(ArticleStatus.auditing);
            } else {
                throw new BusinessException("当前文章只能由审核人撤回");
            }

        } else if (articleDOInSql.getStatus().intValue() == ArticleStatus.auditing) {
            if (Objects.equals(RequestHolder.getCurrentUser().getStaffName(), articleDOInSql.getIssuePerson()) || StringUtils.isEmpty(articleDOInSql.getIssuePerson())) {
                articleDO.setStatus(ArticleStatus.draft);
            } else {
                throw new BusinessException("当前文章只能由审核人撤回");
            }
        } else {
            throw new BusinessException("当前文章已经为编辑状态！");
        }
        articleMapper.updateArticle(articleDO);
    }

    @Override
    public ArticlePreviewDTO previewArticle(BaseIdDTO articleIdDTO) {
        ArticleDO articleDO = ArticleMapStruct.INSTANCE.fromBaseIdDTO(articleIdDTO);
        ArticleDO articleDOInSql = articleMapper.getArticle(articleDO);
        if (null == articleDOInSql) {
            throw new BusinessException("你预览的文章不存在。");
        }
        ArticlePreviewDTO articlePreviewDTO = ArticleMapStruct.INSTANCE.fromArticleDOToArticlePreDTO(articleDOInSql);
        if (null != articleDOInSql.getOrgId()) {
            BaseIdDTO baseIdDTO = new BaseIdDTO();
            baseIdDTO.setId(articleDOInSql.getOrgId());
            OrganizationRespDTO organizationRespDTO = organizationService.getOrganizationDetail(baseIdDTO);
            articlePreviewDTO.setOrgName(organizationRespDTO.getOrgName());
        }
        return articlePreviewDTO;
    }

    @Override
    public void submitArticle(ArticleIdDTO articleIdDTO) {
        articleIdDTO.setAuditOrgId(RequestHolder.getCurrentUser().getOrgId());
        articleIdDTO.setAuditOrgName(RequestHolder.getCurrentUser().getOrgName());
        ArticleDO articleDO = ArticleMapStruct.INSTANCE.fromArticleIdDTO(articleIdDTO);
        ArticleDO articleDOInSql = articleMapper.getArticle(articleDO);
        if (null == articleDOInSql) {
            throw new BusinessException("你提交的文章不存在。");
        }
        if (articleDOInSql.getStatus().intValue() == ArticleStatus.draft ||
                articleDOInSql.getStatus().intValue() == ArticleStatus.rejected) {
            articleDO.setStatus(ArticleStatus.auditing);
            articleMapper.updateArticle(articleDO);
//            // 同步到反饋管理中
//            FeedbackDO feedBackDO = new FeedbackDO();
//            feedBackDO.setTitle(articleDOInSql.getArticleTitle());
//            feedBackDO.setCreator(RequestHolder.getCurrentUser().getStaffName());
//            feedBackDO.setStatus(ReadStatus.unRead);
//            feedBackDO.setId(articleDO.getId());
//            feedBackDO.setArticleContent(articleDOInSql.getArticleContent());
//            feedBackDO.setImageUrl(articleDOInSql.getImageUrl());
//            feedBackDO.setCreateTime(LocalDateTime.now().toString());
//            feedBackDO.setArticleId(articleDO.getId());
//            feedbackMapper.saveFeedback(feedBackDO);

            return;
        }
        throw new BusinessException("只有草稿或被驳回状态的文章才可以提交审核");

    }

    @Override
    public void agreeIssueArticle(BaseIdDTO articleIdDTO) {
        ArticleDO articleDO = ArticleMapStruct.INSTANCE.fromBaseIdDTO(articleIdDTO);
        ArticleDO articleDOInSql = articleMapper.getArticle(articleDO);
        if (null == articleDOInSql) {
            throw new BusinessException("当前文章不存在。");
        }
        articleDO.setIssueTime(LocalDateTime.now().toString());
        articleDO.setIssuePerson(RequestHolder.getCurrentUser().getStaffName());
        if (articleDOInSql.getStatus().intValue() == ArticleStatus.auditing) {
            articleDO.setStatus(ArticleStatus.passed);
            articleMapper.updateArticle(articleDO);
            return;
        }
        throw new BusinessException("只有审核中的文章才能执行此操作。");
    }

    @Override
    public void agreeNoIssueArticle(BaseIdDTO articleIdDTO) {
        ArticleDO articleDO = ArticleMapStruct.INSTANCE.fromBaseIdDTO(articleIdDTO);
        ArticleDO articleDOInSql = articleMapper.getArticle(articleDO);
        if (null == articleDOInSql) {
            throw new BusinessException("当前文章不存在。");
        }
        if (articleDOInSql.getStatus().intValue() == ArticleStatus.auditing) {
            articleDO.setStatus(ArticleStatus.rejected);
            articleMapper.updateArticle(articleDO);
            return;
        }
        throw new BusinessException("只有审核中的文章才能执行此操作。");
    }

    @Override
    public ArticleRespDTO getArticleDetail(BaseIdDTO baseIdDTO) {
        ArticleDO articleDO = ArticleMapStruct.INSTANCE.fromBaseIdDTO(baseIdDTO);
        ArticleDO articleDOInSql = articleMapper.getArticle(articleDO);
        if (null == articleDOInSql) {
            throw new BusinessException("当前文章不存在。");
        }
        ArticleRespDTO articleRespDTO = ArticleMapStruct.INSTANCE.fromArticleDO(articleDOInSql);
        return articleRespDTO;
    }

    @Override
    public void addReadCount(BaseIdDTO articleIdDTO) {
        ArticleDO articleDO = ArticleMapStruct.INSTANCE.fromBaseIdDTO(articleIdDTO);
        ArticleDO articleDOInSql = articleMapper.getArticle(articleDO);
        if (null == articleDOInSql) {
            throw new BusinessException("当前文章不存在。");
        }
        articleMapper.addReadCount(articleDO);
        StatisticsDO statisticsDO = new StatisticsDO();
        statisticsDO.setObjId(articleDOInSql.getId());
        statisticsDO.setObjName(articleDOInSql.getArticleTitle());
        statisticsDO.setType1("文章");
        statisticsDO.setReadCount(1);
        statisticsService.saveStatistic(statisticsDO);

        StaffDO staffDO = RequestHolder.getCurrentUser();
        StaffDO staffDOInSql = staffMapper.queryByStaff(staffDO);
        Integer Count = 0;
        if (staffDOInSql.getArticleReadCount() > 0)
            Count = staffDOInSql.getArticleReadCount();
        staffDOInSql.setArticleReadCount(Count + 1);
        staffMapper.updateStaff(staffDOInSql);
    }

    @Override
    public void addPromotionTimes(BaseIdDTO articleIdDTO) {
        ArticleDO articleDO = ArticleMapStruct.INSTANCE.fromBaseIdDTO(articleIdDTO);
        ArticleDO articleDOInSql = articleMapper.getArticle(articleDO);
        if (null == articleDOInSql) {
            throw new BusinessException("当前文章不存在。");
        }
        articleMapper.addReadCount(articleDO);
        StatisticsDO statisticsDO = new StatisticsDO();
        statisticsDO.setObjId(articleDOInSql.getId());
        statisticsDO.setObjName(articleDOInSql.getArticleTitle());
        statisticsDO.setType1("文章");
        statisticsDO.setPromotionCount(1);
        statisticsService.saveStatistic(statisticsDO);

        StaffDO staffDO = RequestHolder.getCurrentUser();
        StaffDO staffDOInSql = staffMapper.queryByStaff(staffDO);
        Integer Count = 0;
        if (staffDOInSql.getArticlePromotionCount() > 0)
            Count = staffDOInSql.getArticlePromotionCount();
        staffDOInSql.setArticlePromotionCount(Count + 1);
        staffMapper.updateStaff(staffDOInSql);
    }

//    @Override
//    public void releaseIssueArticle(BaseIdDTO articleIdDTO) {
//        ArticleDO articleDO = ArticleMapStruct.INSTANCE.fromBaseIdDTO(articleIdDTO);
//        ArticleDO articleDOInSql = articleMapper.getArticle(articleDO);
//        if(null == articleDOInSql) {
//            throw new BusinessException("当前文章不存在。");
//        }
//        articleDO.setIssueTime(LocalDateTime.now().toString());
//        articleDO.setIssuePerson(RequestHolder.getCurrentUser().getStaffName());
//        if(articleDOInSql.getStatus().intValue() == ArticleStatus.to_be_released) {
//            articleDO.setStatus(ArticleStatus.released);
//            articleMapper.updateArticle(articleDO);
//            return;
//        }
//        throw new BusinessException("只有待发布的文章才能执行此操作。");
//    }

    private boolean checkArticleTitleExist(ArticleDO articleDO) {
        return articleMapper.countByArticleTitle(articleDO) > 0;
    }


}
